<?php

/*
 * Copyright 2008 the original author or authors.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#namespace tehframework\request\web;

#use tehframework\request\RequestBuilder;

class WebRequestBuilder extends RequestBuilder
{
	/**
	 * @return WebRequest
	 */
	public function buildRequest()
	{
		$request = new WebRequest(
			$this->resolveMethod(), $this->resolveParameters()
		);
		
		$request
			->setCookies($this->resolveCookies())
			->setHeaders($this->resolveHeaders())
			->setFiles($this->resolveFiles());
		
		return $request;
	}
	
	/**
	 * @return Request::METHOD_*
	 */
	private function resolveMethod()
	{
		$method = isset($_SERVER['REQUEST_METHOD'])
			? $_SERVER['REQUEST_METHOD'] : null;
		
		if (isset($_POST['REQUEST_METHOD']))
		{
			$method = strtoupper($_POST['REQUEST_METHOD']);
		}
		
		switch ($method)
		{
			case WebRequest::METHOD_CREATE:
			case 'PUT':
				return WebRequest::METHOD_CREATE;
			
			case WebRequest::METHOD_REMOVE:
			case 'DELETE':
				return WebRequest::METHOD_REMOVE;
			
			case WebRequest::METHOD_WRITE:
			case 'POST':
				return WebRequest::METHOD_WRITE;
			
			default:
				return WebRequest::METHOD_READ;
		}
	}
	
	/**
	 * @return array<string,mixed>
	 */
	private function resolveParameters()
	{
		return $_POST + $_GET;
	}
	
	/**
	 * @return array<string,string>
	 */
	private function resolveCookies()
	{
		return $_COOKIE;
	}
	
	/**
	 * @return array<string,string>
	 */
	private function resolveHeaders()
	{
		$headers = array();
		
		foreach ($_SERVER as $key => $value)
		{
			if (substr($key, 0, 5) == 'HTTP_')
			{
				$headers[substr($key, 5)] = $value;
			}
		}
		
		return $headers;
	}
	
	/**
	 * @return array<string,UploadedFile[]>
	 * @todo
	 */
	private function resolveFiles()
	{
		return array();
	}
}